import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import {
    Grid,
    Card,
    Button,
    Tag,
    Badge,
    Toast,
    Rate,
    Skeleton
} from 'antd-mobile';
import {
    CalendarOutlined,
    UserOutlined,
    FileTextOutlined,
    ShoppingCartOutlined,
    BookOutlined,
    StarOutlined,
    SettingOutlined,
    BellOutlined,
    SearchOutlined,
    HomeOutlined,
    CommentOutlined,
    EyeOutlined,
    ProductOutlined 
} from '@ant-design/icons';
import './index.css';
import { get_all_product_package } from '../../services/product'; // 接口

// Banner数据
const bannerList = [
    {
        url: 'https://picsum.photos/id/26/750/300',
        title: '春季养生特惠',
        subTitle: '推拿理疗套餐立减50元',
        tag: '限时'
    },
    {
        url: 'https://picsum.photos/id/28/750/300',
        title: '肩颈调理专项',
        subTitle: '久坐人群必选',
        tag: '畅销'
    },
    {
        url: 'https://picsum.photos/id/30/750/300',
        title: '新客首单8折',
        subTitle: '中医理疗体验券',
        tag: '新人'
    }
];

// 功能入口数据
const featureList = [
    { icon: <CalendarOutlined />, label: '预约理疗', badge: 3 },
    { icon: <UserOutlined />, label: '医师团队' },
    { icon: <FileTextOutlined />, label: '健康档案' },
    { icon: <ShoppingCartOutlined />, label: '我的套餐' },
    { icon: <BookOutlined />, label: '养生知识', badge: 5 },
    { icon: <StarOutlined />, label: '我的评价' },
    { icon: <SettingOutlined />, label: '设置' }
];

// 养生知识文章数据
const healthArticles = [
    {
        id: 1,
        title: '春季养生：肝木旺盛时节的经络调理法',
        desc: '春季对应五行之木，主肝藏血。此时需注重疏肝理气，可通过按揉太冲穴、泡脚加艾草等方式调理...',
        img: 'https://picsum.photos/id/292/200/200',
        views: '2.3k',
        comments: '56',
        date: '2024-03-15',
        category: '四季养生'
    },
    {
        id: 2,
        title: '久坐人群必看：3个穴位缓解肩颈僵硬',
        desc: '长期久坐易导致肩颈气血瘀滞，每天按揉肩井穴、天宗穴、风池穴各3分钟，配合简单拉伸，有效改善酸痛...',
        img: 'https://picsum.photos/id/177/200/200',
        views: '1.8k',
        comments: '42',
        date: '2024-03-10',
        category: '穴位调理'
    },
    {
        id: 3,
        title: '艾灸的正确打开方式：不同体质对应不同灸法',
        desc: '虚寒体质适合隔姜灸，湿热体质需先清热再温和灸，阴虚火旺者慎用艾灸。一文教你判断自身体质选对灸法...',
        img: 'https://picsum.photos/id/152/200/200',
        views: '3.1k',
        comments: '78',
        date: '2024-03-05',
        category: '艾灸养生'
    },
    {
        id: 4,
        title: '中医食疗：4款祛湿汤品，告别身体困重',
        desc: '体内湿气重易导致疲劳、舌苔厚腻，推荐茯苓薏米汤、红豆芡实汤等4款食疗方，简单易做，适合日常调理...',
        img: 'https://picsum.photos/id/292/200/200',
        views: '2.5k',
        comments: '63',
        date: '2024-02-28',
        category: '食疗养生'
    }
];

const Home = () => {
    // 状态管理
    const [currentBanner, setCurrentBanner] = useState(0);
    const [collectedProjects, setCollectedProjects] = useState([]);
    const [isScrolled, setIsScrolled] = useState(false);
    const [recommendProjects, setRecommendProjects] = useState([]); // 动态项目数据
    const [loading, setLoading] = useState(true); // 加载状态
    const [error, setError] = useState(null); // 错误状态
    const bannerRef = useRef(null);
    const navigate = useNavigate();

    // 监听滚动事件
    useEffect(() => {
        const handleScroll = () => {
            setIsScrolled(window.scrollY > 50);
        };
        window.addEventListener('scroll', handleScroll);
        return () => window.removeEventListener('scroll', handleScroll);
    }, []);

    // 自动轮播逻辑
    useEffect(() => {
        const timer = setInterval(() => {
            setCurrentBanner(prev => (prev + 1) % bannerList.length);
        }, 3000);
        return () => clearInterval(timer);
    }, []);

    // 从接口获取推荐项目数据
    useEffect(() => {
        const fetchProjects = async () => {
            try {
                setLoading(true);
                setError(null);

                // 调用接口获取数据，这里假设接口返回格式与我们需要的字段匹配
                // 可以根据实际接口返回调整参数和数据处理
                const response = await get_all_product_package({
                    // page: 1,
                    // limit: 6,
                    // key: 'recommend' // 假设传recommend获取推荐项目
                });

                if (response.code === 0) {
                    setRecommendProjects(response.data.data);
                } else {
                    setError('获取推荐项目失败');
                    console.error('接口返回异常:', response);
                }
            } catch (err) {
                console.error('请求失败:', err);
            } finally {
                setLoading(false);
            }
        };

        fetchProjects();
    }, []);

    // 收藏/取消收藏项目
    const toggleCollect = (id) => {
        if (collectedProjects.includes(id)) {
            setCollectedProjects(collectedProjects.filter(item => item !== id));
            Toast.show('已取消收藏');
        } else {
            setCollectedProjects([...collectedProjects, id]);
            Toast.show('收藏成功');
        }
    };

    // 快速预约功能
    const quickBooking = (id) => {
        navigate("/appointment/appointmentfrom/"+id)
    };

    // 跳转到文章详情页
    const goToArticleDetail = (articleId) => {
        navigate(`/articledetail`);
    };

    // 跳转到养生知识列表页
    const goToArticleList = () => {
        navigate("/health/articles");
    };

    // 加载中的骨架屏
    const renderProjectSkeleton = () => {
        return Array(3).fill(0).map((_, index) => (
            <Card key={`skeleton-${index}`} className="project-card">
                <div className="project-img-container">
                    <Skeleton className="skeleton-img" height={160} />
                </div>
                <div className="project-info">
                    <Skeleton className="skeleton-title" height={24} width="70%" />
                    <Skeleton className="skeleton-desc" height={40} style={{ marginTop: 8 }} />
                    <div className="project-meta" style={{ marginTop: 8 }}>
                        <Skeleton className="skeleton-price" height={20} width="30%" />
                    </div>
                    <Skeleton className="skeleton-btn" height={40} style={{ marginTop: 12 }} />
                </div>
            </Card>
        ));
    };

    return (
        <div className="home-container">
            {/* 顶部导航栏 */}
            <header className={`top-nav ${isScrolled ? 'scrolled' : ''}`}>
                <div className="flex items-center">
                    <h1 className="ml-2 text-xl font-bold text-brown-primary"><i className="fa fa-leaf text-white text-3xl"></i> 本草轩理疗坊</h1>
                </div>
                <div className="nav-actions">
                    <div size="small" className="search-btn" onClick={() => {
                        navigate("/search")
                    }}>
                        <SearchOutlined />
                    </div>
                    <div size="small" className="message-btn">
                        <BellOutlined />
                    </div>
                </div>
            </header>

            {/* 顶部Banner轮播 */}
            <div className="banner-wrapper" ref={bannerRef}>
                <div className="banner-container">
                    {bannerList.map((item, index) => (
                        <div
                            key={index}
                            className={`banner-item ${index === currentBanner ? 'active' : ''}`}
                            style={{ opacity: index === currentBanner ? 1 : 0 }}
                        >
                            <img src={item.url} alt={item.title} className="banner-img" />
                            {item.tag && (
                                <Tag className="banner-tag">{item.tag}</Tag>
                            )}
                            <div className="banner-text">
                                <h2>{item.title}</h2>
                                <p>{item.subTitle}</p>
                            </div>
                        </div>
                    ))}
                    <div className="banner-indicators">
                        {bannerList.map((_, index) => (
                            <span
                                key={index}
                                className={index === currentBanner ? 'active' : ''}
                                onClick={() => setCurrentBanner(index)}
                                aria-label={`切换到第${index + 1}张轮播图`}
                            />
                        ))}
                    </div>
                </div>
            </div>

            {/* 功能入口网格 */}
            <div className="section-container">
                <Grid
                    columns={4}
                    data={featureList}
                    renderItem={(item) => (
                        <div
                            className="feature-item"
                            onClick={() => {
                                if (item.label === '养生知识') {
                                    goToArticleList();
                                } else {
                                    Toast.show(`即将跳转到${item.label}`);
                                }
                            }}
                        >
                            <div className="feature-icon-container">
                                <span className="feature-icon">{item.icon}</span>
                                {item.badge && (
                                    <Badge className="feature-badge">{item.badge}</Badge>
                                )}
                            </div>
                            <div className="feature-label">{item.label}</div>
                        </div>
                    )}
                />
            </div>

            {/* 动态推荐理疗项目 */}
            <div className="section-container">
                <div className="section-header">
                    <h3 className="section-title">推荐理疗项目</h3>
                    <div className="more-btn" size="small">查看全部</div>
                </div>

                {error && (
                    <div className="error-message">
                        <p>{error}</p>
                        <Button onClick={() => window.location.reload()}>重试</Button>
                    </div>
                )}

                <div className="projects-list">
                    {loading ? (
                        renderProjectSkeleton()
                    ) : recommendProjects.length > 0 ? (
                        recommendProjects.map((project) => (
                            <Card key={project.id} className="project-card">
                                <div className="project-img-container">
                                    <img
                                        onClick={() => navigate('/project/projectdetail/'+project.id)}
                                        src={project.photo || 'https://picsum.photos/id/237/300/200'} //  fallback图片
                                        alt={project.name}
                                        className="project-img"
                                    />
                                    {project.tag && (
                                        <Tag className={`project-tag ${project.tag.toLowerCase()}`}>
                                            热门
                                        </Tag>
                                    )}
                                    <div
                                        className="collect-btn"
                                        size="small"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            toggleCollect(project.id);
                                        }}
                                    >
                                        {collectedProjects.includes(project.id) ? '❤️' : '♡'}
                                    </div>
                                    <div className="project-sales">
                                        已售 {project.sales || 0}+
                                    </div>
                                </div>
                                <div className="project-info">
                                    <h4 className="project-title">{project.name}</h4>
                                    <p className="project-desc">{project.description}</p>
                                    <div className="project-meta">
                                        <span className="project-price">¥{project.price}</span>
                                        {project.originalPrice && (
                                            <span className="original-price">¥{project.originalPrice}</span>
                                        )}
                                        <span className="project-duration">{project.duration || '30分钟'}</span>
                                    </div>
                                    <div
                                        className="book-btn"
                                        onClick={() => quickBooking(project.id)}
                                    >
                                        立即预约
                                    </div>
                                </div>
                            </Card>
                        ))
                    ) : (
                        <div className="no-data">
                            <ProductOutlined  className="no-data-icon" />
                            <p>暂无推荐理疗项目</p>
                        </div>
                    )}
                </div>
            </div>

            {/* 养生知识文章模块 */}
            <div className="section-container">
                <div className="section-header">
                    <h3 className="section-title">养生知识推荐</h3>
                    <div
                        className="more-btn"
                        size="small"
                        onClick={goToArticleList}
                    >
                        查看全部
                    </div>
                </div>
                <div className="articles-list">
                    {healthArticles.map((article) => (
                        <Card key={article.id} className="article-card" onClick={() => goToArticleDetail(article.id)}>
                            <div className="article-content">
                                <div className="article-img-wrapper">
                                    <img src={article.img} alt={article.title} className="article-img" />
                                </div>
                                <div className="article-info">
                                    <Tag className="article-category-tag">{article.category}</Tag>
                                    <h4 className="article-title">{article.title}</h4>
                                    <p className="article-desc">{article.desc}</p>
                                    <div className="article-meta">
                                        <div className="meta-item">
                                            <BookOutlined size="small" />
                                            <span>{article.date}</span>
                                        </div>
                                        <div className="meta-item">
                                            <EyeOutlined size="small" />
                                            <span>{article.views} 阅读</span>
                                        </div>
                                        <div className="meta-item">
                                            <CommentOutlined size="small" />
                                            <span>{article.comments} 评论</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </Card>
                    ))}
                </div>
            </div>

        </div>
    );
};

export default Home;
